package com.bz.common;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bz.entity.UserEntity;
import com.bz.security.AuthUserDto;
import com.bz.security.ThreadLocalUtils;

public class UserConfig {

    /**
     * redis key 前缀
     */
    private static String USER_INFO = "user";

    public static String getUserKey(String username) {
        return USER_INFO + ":" + username;
    }

    public static UserEntity convertUser(AuthUserDto u) {
        if (u == null) {
            return null;
        }
        UserEntity user = new UserEntity();
        user.setId(u.getId());
        user.setUsername(u.getUsername());
        user.setPhone(u.getPhone());
        user.setName(u.getName());
        user.setUrls(u.getUrls());
        user.setRoleMap(u.getRoleMap());
        return user;
    }

    public static UserEntity getLoginUser() {
        RedisServiceUtil redisServiceUtil = ApplicationContextProvider.getBean(RedisServiceUtil.class);
        CommonHeader header = ThreadLocalUtils.get();
        if (null == header) {
            return null;
        }
        String ustr = redisServiceUtil.get(UserConfig.getUserKey(header.getUsername()));
        if (StringUtils.isNotEmpty(ustr)) {
            return JSON.parseObject(ustr, UserEntity.class);
        }
        return null;
    }

    public static UserEntity getLoginUser(String userName) {
        RedisServiceUtil redisServiceUtil = ApplicationContextProvider.getBean(RedisServiceUtil.class);
        String ustr = redisServiceUtil.get(UserConfig.getUserKey(userName));
        if (StringUtils.isNotEmpty(ustr)) {
            return JSON.parseObject(ustr, UserEntity.class);
        }
        return null;
    }

}
